<template>
  <div class="security-management">
    <div class="page-header">
      <h2>安防设备管理</h2>
      <Space>
        <Button @click="refreshDevices">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新状态
        </Button>
        <Button type="primary" @click="showAddDeviceModal = true">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加设备
        </Button>
      </Space>
    </div>

    <!-- 安防设备统计 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="设备总数"
          :value="statistics.totalDevices"
          :change="statistics.totalChange"
          icon="ant-design:safety-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="在线设备"
          :value="statistics.onlineDevices"
          :change="statistics.onlineChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="离线设备"
          :value="statistics.offlineDevices"
          :change="statistics.offlineChange"
          icon="ant-design:close-circle-outlined"
          color="#f5222d"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="今日告警"
          :value="statistics.todayAlerts"
          :change="statistics.alertsChange"
          icon="ant-design:warning-outlined"
          color="#faad14"
        />
      </Col>
    </Row>

    <!-- 实时监控面板 -->
    <Row :gutter="16" class="monitoring-panel">
      <Col :span="16">
        <Card title="实时监控" class="monitoring-card">
          <div class="monitoring-content">
            <div class="camera-grid">
              <div
                v-for="camera in cameras"
                :key="camera.id"
                class="camera-item"
                :class="camera.status"
              >
                <div class="camera-header">
                  <span class="camera-name">{{ camera.name }}</span>
                  <Tag :color="getStatusColor(camera.status)">
                    {{ getStatusText(camera.status) }}
                  </Tag>
                </div>
                <div class="camera-view">
                  <div class="camera-placeholder">
                    <IconifyIcon
                      icon="ant-design:video-camera-outlined"
                      class="camera-icon"
                    />
                    <p>{{ camera.location }}</p>
                  </div>
                </div>
                <div class="camera-actions">
                  <Button type="link" size="small" @click="viewCamera(camera)">
                    查看
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    @click="controlCamera(camera)"
                  >
                    控制
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    @click="recordCamera(camera)"
                  >
                    录像
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="8">
        <Card title="告警信息" class="alerts-card">
          <div class="alerts-list">
            <div
              v-for="alert in securityAlerts"
              :key="alert.id"
              class="alert-item"
              :class="alert.level"
            >
              <div class="alert-icon">
                <IconifyIcon :icon="getAlertIcon(alert.level)" />
              </div>
              <div class="alert-content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="alert-desc">{{ alert.description }}</div>
                <div class="alert-time">{{ alert.time }}</div>
              </div>
              <div class="alert-actions">
                <Button type="link" size="small" @click="handleAlert(alert)">
                  处理
                </Button>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 设备列表 -->
    <Card title="设备列表" class="devices-list-card">
      <div class="list-header">
        <Form layout="inline" :model="searchForm" class="search-form">
          <FormItem label="设备名称">
            <Input
              v-model:value="searchForm.name"
              placeholder="请输入设备名称"
              allow-clear
            />
          </FormItem>
          <FormItem label="设备类型">
            <Select
              v-model:value="searchForm.type"
              placeholder="请选择类型"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="camera">摄像头</SelectOption>
              <SelectOption value="access">门禁</SelectOption>
              <SelectOption value="alarm">报警器</SelectOption>
              <SelectOption value="sensor">传感器</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="设备状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="online">在线</SelectOption>
              <SelectOption value="offline">离线</SelectOption>
              <SelectOption value="alarm">告警</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="安装位置">
            <Input
              v-model:value="searchForm.location"
              placeholder="请输入安装位置"
              allow-clear
            />
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleSearch">
                <IconifyIcon icon="ant-design:search-outlined" />
                搜索
              </Button>
              <Button @click="handleReset">
                <IconifyIcon icon="ant-design:reload-outlined" />
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>
      <Table
        :columns="columns"
        :data-source="filteredDevices"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="device-info">
              <div class="device-name">{{ record.name }}</div>
              <div class="device-id">ID: {{ record.deviceId }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'location'">
            <div class="location-info">
              <IconifyIcon icon="ant-design:environment-outlined" />
              <span>{{ record.location }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'lastUpdate'">
            <div class="update-info">
              <span class="update-time">{{ record.lastUpdate }}</span>
              <span class="update-status" :class="record.status">
                {{ getUpdateStatusText(record.status) }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDevice(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="controlDevice(record)">
                控制
              </Button>
              <Button type="link" size="small" @click="editDevice(record)">
                编辑
              </Button>
              <Button type="link" size="small" @click="restartDevice(record)">
                重启
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 添加设备弹窗 -->
    <Modal
      v-model:open="showAddDeviceModal"
      title="添加安防设备"
      width="700px"
      @ok="handleSaveDevice"
      @cancel="handleCancelDevice"
    >
      <Form
        ref="deviceFormRef"
        :model="deviceForm"
        :rules="deviceRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="设备名称" name="name">
              <Input
                v-model:value="deviceForm.name"
                placeholder="请输入设备名称"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="设备类型" name="type">
              <Select
                v-model:value="deviceForm.type"
                placeholder="请选择设备类型"
              >
                <SelectOption value="camera">摄像头</SelectOption>
                <SelectOption value="access">门禁</SelectOption>
                <SelectOption value="alarm">报警器</SelectOption>
                <SelectOption value="sensor">传感器</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="设备型号" name="model">
              <Input
                v-model:value="deviceForm.model"
                placeholder="请输入设备型号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="设备厂商" name="manufacturer">
              <Input
                v-model:value="deviceForm.manufacturer"
                placeholder="请输入设备厂商"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="安装位置" name="location">
              <Input
                v-model:value="deviceForm.location"
                placeholder="请输入安装位置"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="IP地址" name="ipAddress">
              <Input
                v-model:value="deviceForm.ipAddress"
                placeholder="请输入IP地址"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="端口号" name="port">
              <Input
                v-model:value="deviceForm.port"
                placeholder="请输入端口号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="设备状态" name="status">
              <Select
                v-model:value="deviceForm.status"
                placeholder="请选择设备状态"
              >
                <SelectOption value="online">在线</SelectOption>
                <SelectOption value="offline">离线</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="设备描述" name="description">
          <Textarea
            v-model:value="deviceForm.description"
            placeholder="请输入设备描述"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';

// 状态管理
const loading = ref(false);
const showAddDeviceModal = ref(false);
const isEdit = ref(false);

// 表单引用
const deviceFormRef = ref();

// 统计数据
const statistics = reactive({
  totalDevices: 28,
  totalChange: 3,
  onlineDevices: 25,
  onlineChange: 2,
  offlineDevices: 3,
  offlineChange: -1,
  todayAlerts: 8,
  alertsChange: 2,
});

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  location: '',
});

// 设备表单
const deviceForm = reactive({
  name: '',
  type: '',
  model: '',
  manufacturer: '',
  location: '',
  ipAddress: '',
  port: '',
  status: 'online',
  description: '',
});

// 表单验证规则
const deviceRules = {
  name: [{ required: true, message: '请输入设备名称' }],
  type: [{ required: true, message: '请选择设备类型' }],
  location: [{ required: true, message: '请输入安装位置' }],
  ipAddress: [{ required: true, message: '请输入IP地址' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 摄像头数据
const cameras = ref([
  {
    id: 1,
    name: '大厅摄像头',
    location: '1楼大厅',
    status: 'online',
  },
  {
    id: 2,
    name: '电梯摄像头',
    location: '电梯间',
    status: 'online',
  },
  {
    id: 3,
    name: '停车场摄像头',
    location: '地下停车场',
    status: 'offline',
  },
  {
    id: 4,
    name: '后门摄像头',
    location: '后门',
    status: 'online',
  },
]);

// 安防告警数据
const securityAlerts = ref([
  {
    id: 1,
    level: 'critical',
    title: '门禁异常',
    description: '后门门禁系统检测到异常开门',
    time: '2分钟前',
  },
  {
    id: 2,
    level: 'warning',
    title: '摄像头离线',
    description: '停车场摄像头设备离线',
    time: '5分钟前',
  },
  {
    id: 3,
    level: 'info',
    title: '传感器触发',
    description: '101房间烟雾传感器触发',
    time: '10分钟前',
  },
]);

// 设备数据
const devices = ref([
  {
    id: 1,
    name: '大厅摄像头',
    deviceId: 'CAM001',
    type: 'camera',
    status: 'online',
    location: '1楼大厅',
    lastUpdate: '2024-01-19 15:30',
    model: 'IPC-2000',
    manufacturer: '海康威视',
    ipAddress: '192.168.1.101',
  },
  {
    id: 2,
    name: '电梯门禁',
    deviceId: 'ACCESS001',
    type: 'access',
    status: 'online',
    location: '电梯间',
    lastUpdate: '2024-01-19 15:30',
    model: 'AC-100',
    manufacturer: '海康威视',
    ipAddress: '192.168.1.102',
  },
  {
    id: 3,
    name: '停车场摄像头',
    deviceId: 'CAM002',
    type: 'camera',
    status: 'offline',
    location: '地下停车场',
    lastUpdate: '2024-01-19 14:25',
    model: 'IPC-2000',
    manufacturer: '海康威视',
    ipAddress: '192.168.1.103',
  },
  {
    id: 4,
    name: '烟雾报警器',
    deviceId: 'ALARM001',
    type: 'alarm',
    status: 'online',
    location: '1楼走廊',
    lastUpdate: '2024-01-19 15:30',
    model: 'SM-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.104',
  },
]);

// 表格列定义
const columns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '设备状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '安装位置',
    dataIndex: 'location',
    key: 'location',
    width: 150,
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 过滤后的设备数据
const filteredDevices = computed(() => {
  let result = devices.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.location) {
    result = result.filter((item) =>
      item.location.toLowerCase().includes(searchForm.location.toLowerCase()),
    );
  }

  return result;
});

// 类型相关函数
const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    camera: 'blue',
    access: 'green',
    alarm: 'red',
    sensor: 'orange',
  };
  return colors[type] || 'default';
};

const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    camera: '摄像头',
    access: '门禁',
    alarm: '报警器',
    sensor: '传感器',
  };
  return texts[type] || type;
};

// 状态相关函数
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    online: 'green',
    offline: 'red',
    alarm: 'orange',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '在线',
    offline: '离线',
    alarm: '告警',
  };
  return texts[status] || status;
};

const getUpdateStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '正常',
    offline: '离线',
    alarm: '告警',
  };
  return texts[status] || status;
};

// 告警相关函数
const getAlertIcon = (level: string) => {
  const icons: Record<string, string> = {
    critical: 'ant-design:close-circle-outlined',
    warning: 'ant-design:warning-outlined',
    info: 'ant-design:info-circle-outlined',
  };
  return icons[level] || 'ant-design:info-circle-outlined';
};

// 事件处理函数
const refreshDevices = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    message.success('设备状态刷新完成');
  }, 1000);
};

const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
    location: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSaveDevice = async () => {
  try {
    await deviceFormRef.value.validate();
    if (isEdit.value) {
      message.success('设备信息更新成功');
    } else {
      message.success('设备添加成功');
    }
    showAddDeviceModal.value = false;
    resetDeviceForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancelDevice = () => {
  showAddDeviceModal.value = false;
  resetDeviceForm();
};

const viewDevice = (record: any) => {
  message.info(`查看设备详情: ${record.name}`);
};

const controlDevice = (record: any) => {
  message.info(`控制设备: ${record.name}`);
};

const editDevice = (record: any) => {
  isEdit.value = true;
  Object.assign(deviceForm, record);
  showAddDeviceModal.value = true;
};

const restartDevice = (record: any) => {
  message.success(`设备"${record.name}"重启成功`);
};

const viewCamera = (camera: any) => {
  message.info(`查看摄像头: ${camera.name}`);
};

const controlCamera = (camera: any) => {
  message.info(`控制摄像头: ${camera.name}`);
};

const recordCamera = (camera: any) => {
  message.success(`摄像头"${camera.name}"开始录像`);
};

const handleAlert = (alert: any) => {
  message.success(`告警"${alert.title}"已处理`);
};

const resetDeviceForm = () => {
  Object.assign(deviceForm, {
    name: '',
    type: '',
    model: '',
    manufacturer: '',
    location: '',
    ipAddress: '',
    port: '',
    status: 'online',
    description: '',
  });
  isEdit.value = false;
};

onMounted(() => {
  // 初始化数据
  pagination.total = devices.value.length;
});
</script>

<style scoped>
.security-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.monitoring-panel {
  margin-bottom: 24px;
}

.monitoring-card {
  height: 500px;
}

.monitoring-content {
  height: 100%;
}

.camera-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
  height: 100%;
}

.camera-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
}

.camera-item.online {
  border-color: #52c41a;
}

.camera-item.offline {
  border-color: #f5222d;
}

.camera-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.camera-name {
  font-weight: 500;
}

.camera-view {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  min-height: 150px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.camera-placeholder {
  color: #999;
  text-align: center;
}

.camera-icon {
  margin-bottom: 8px;
  font-size: 32px;
}

.camera-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.alerts-card {
  height: 500px;
}

.alerts-list {
  max-height: 400px;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 6px;
}

.alert-item.critical {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
}

.alert-item.warning {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
}

.alert-item.info {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.alert-icon {
  margin-top: 2px;
  font-size: 16px;
}

.alert-item.critical .alert-icon {
  color: #f5222d;
}

.alert-item.warning .alert-icon {
  color: #faad14;
}

.alert-item.info .alert-icon {
  color: #52c41a;
}

.alert-content {
  flex: 1;
}

.alert-title {
  margin-bottom: 4px;
  font-weight: 500;
}

.alert-desc {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.alert-time {
  font-size: 12px;
  color: #999;
}

.alert-actions {
  display: flex;
  align-items: center;
}

.devices-list-card {
  margin-bottom: 16px;
}

.list-header {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.device-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.device-name {
  font-weight: 500;
  color: #1890ff;
  cursor: pointer;
}

.device-name:hover {
  text-decoration: underline;
}

.device-id {
  font-size: 12px;
  color: #999;
}

.location-info {
  display: flex;
  gap: 4px;
  align-items: center;
}

.update-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.update-time {
  font-size: 12px;
  color: #666;
}

.update-status {
  font-size: 12px;
  font-weight: 500;
}

.update-status.online {
  color: #52c41a;
}

.update-status.offline {
  color: #f5222d;
}

.update-status.alarm {
  color: #faad14;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
